<template>
  <div class="app-container">
    <div>
      <el-dialog
        :title="title"
        :visible.sync="open"
        :before-close="close"
        width="35%"
      >
        <el-form :model="data" :rules="rules" label-position="left" label-width="80px">
          <div style="margin-top: -20px; margin-bottom: 40px">
            <el-divider>基础信息</el-divider>
          </div>
          <el-form-item label="* 计划名称" prop="planName">
            <el-input v-model="data.planName" placeholder="请输入计划名称"/>
          </el-form-item>
          <el-form-item label="* 计划分类" prop="trainCategoryId">
            <el-select v-model="data.trainCategoryId" placeholder="请选择计划分类" style="width: 100%">
              <el-option
                v-for="item in dict.type.train_plan_train_category"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="* 知识分类" prop="knowledgeCategoryId">
            <el-cascader v-model="data.knowledgeCategoryId" placeholder="请选择知识分类" style="width: 100%"
                         :options="categories" :props="{value: 'id', label: 'title'}"/>
          </el-form-item>
          <el-form-item label="* 起止时间" prop="planName">
            <el-date-picker
              v-model="timeRange"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始时间"
              value-format="yyyy-MM-dd HH:mm:ss"
              end-placeholder="结束时间"
              style="width: 100%">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="* 培训工时" prop="trainWorkHours">
            <el-input v-model="data.trainWorkHours" placeholder="请输入培训工时"/>
          </el-form-item>
          <el-form-item label="* 培训讲师" prop="trainLecturer">
            <el-input v-model="data.trainLecturer" placeholder="请输入培训讲师"/>
          </el-form-item>
          <el-form-item label="* 参与人" prop="trainDirectorId">
            <el-button @click="handleUserClick(0)" type="primary" size="small" icon="el-icon-plus" plain>选择参与人
            </el-button>
          </el-form-item>
          <el-form-item prop="trainDirectorId" v-if="participants.length > 0">
            <div>
              <div>
                用户：
              </div>
              <el-tag style="margin: 5px" type="info" v-for="(item, index) in participants" :key="index" closable
                      @close="removeParticipant(index)"> {{ item.nickName }}
              </el-tag>
            </div>
            <div>
              <div>
                部门：
              </div>
              <el-tag style="margin: 5px" type="danger" v-for="(item, index) in userDepts" :key="index"> {{
                  item
                }}
              </el-tag>
            </div>
          </el-form-item>
          <el-form-item v-if="data.userDepts" label="参与部门">

          </el-form-item>
          <div style="margin: 40px 0">
            <el-divider>培训信息</el-divider>
          </div>
          <el-form-item label="* 培训类型" prop="trainType">
            <el-radio-group v-model="data.trainType">
              <el-radio :label="'0'">无培训</el-radio>
              <el-radio :label="'1'">线上培训</el-radio>
              <el-radio :label="'2'">线下培训</el-radio>
            </el-radio-group>
          </el-form-item>
          <div v-if="data.trainType === '1'">
            <el-form-item label="* 课程" prop="planName">
              <el-button @click="courseModalShow = true" type="primary" size="small" icon="el-icon-plus" plain>
                选择课程
              </el-button>
            </el-form-item>
            <el-form-item prop="planName">
              <el-tag v-for="(item, index) in courseList" :key="index" type="primary" style="margin-right: 5px"
                      @close="removeCourse(index)"
                      closable>{{ item.title }}
              </el-tag>
            </el-form-item>
          </div>
          <div v-if="data.trainType === '2'">
            <el-form-item label="* 负责人" prop="planName">
              <el-button @click="handleUserClick(1)" type="primary" size="small" plain>{{
                  Object.keys(trainDirector).length !== 0 ? trainDirector.nickName : '选择培训负责人'
                }}
              </el-button>
            </el-form-item>
            <el-form-item label="* 讲师" prop="lecturer">
              <el-input v-model="data.offlineTrainLecturer" placeholder="请输入讲师名称" style="width: 100%"/>
            </el-form-item>
            <el-form-item label="* 地点" prop="lecturer">
              <el-input v-model="data.offlineTrainLocation" placeholder="请输入培训地点" style="width: 100%"/>
            </el-form-item>
          </div>
          <div style="margin: 40px 0">
            <el-divider>考试信息</el-divider>
          </div>
          <el-form-item label="* 考试类型" prop="examType">
            <el-radio-group v-model="data.examType">
              <el-radio :label="'0'">无考试</el-radio>
              <el-radio :label="'1'">线上考试</el-radio>
              <el-radio :label="'2'">线下考试</el-radio>
            </el-radio-group>
          </el-form-item>
          <div v-if="data.examType === '1'">
            <el-form-item label="* 考题类型" prop="examQuestionType">
              <el-radio-group v-model="data.onlineExamType">
                <el-radio :label="'1'">自选试卷</el-radio>
                <el-radio :label="'2'">随机题库</el-radio>
              </el-radio-group>
            </el-form-item>
            <div v-if="data.onlineExamType === '1'">
              <el-form-item prop="planName">
                <el-button @click="testPaperModalOpen = true" type="primary" size="small" icon="el-icon-plus" plain>
                  选择试卷
                </el-button>
              </el-form-item>
              <el-form-item prop="planName">
                <el-tag v-for="(item, index) in testPapers" :key="index" type="primary" style="margin-right: 5px"
                        @close="removeTestPaper(index)"
                        closable>{{ item.name }}
                </el-tag>
              </el-form-item>
            </div>
            <div v-if="data.onlineExamType === '2'">
              <el-form-item prop="planName">
                <el-button @click="libraryModalOpen = true" type="primary" size="small" icon="el-icon-plus" plain>
                  题库配置
                </el-button>
              </el-form-item>
              <el-form-item prop="planName">
                <div v-show="Object.keys(questionLibraryRules).length > 0"
                     style="display: flex; justify-content: space-between">
                  <div>总分：{{ questionLibraryRules.fraction }}分</div>
                  <div>合格分数：{{ questionLibraryRules.passFraction }}分</div>
                </div>
                <div v-for="(item, index) in questionLibraryRules.options" :key="index">
                  <div style="box-shadow: 0 0 10px #dcd5d5; border-radius: 10px; padding: 10px; margin-bottom: 10px">
                    <div style="border-bottom: 1px #dcd5d5 solid">
                      <span>{{ item.typeDesc }}</span>
                      <span> 共{{ item.totalNum }}题，分值：{{ item.score }}分 </span>
                    </div>
                    <div v-for="t in item.tags">
                      <el-tag size="small" style="margin-right: 5px">{{ t.tagName }}</el-tag>
                      <span>{{ t.num }}道题</span>
                    </div>
                  </div>
                </div>
              </el-form-item>
            </div>
          </div>
          <div v-if="data.examType === '2'">
            <el-form-item label="* 负责人">
              <el-button @click="handleUserClick(2)" type="primary" size="small" plain>
                {{ Object.keys(examDirector).length !== 0 ? examDirector.nickName : '选择考试负责人' }}
              </el-button>
            </el-form-item>
            <el-form-item label="* 考官" prop="offlineExamLecturer">
              <el-input v-model="data.offlineExamLecturer" placeholder="请输入考官名称" style="width: 100%"/>
            </el-form-item>
            <el-form-item label="* 地点" prop="offlineExamLocation">
              <el-input v-model="data.offlineExamLocation" placeholder="请输入考试地点" style="width: 100%"/>
            </el-form-item>
          </div>
        </el-form>

        <div style="text-align: right;">
          <el-button @click="close">取 消</el-button>
          <el-button type="primary" @click="submit" :loading="submitLoading">{{
              submitLoading ? '提交中 ...' : '确 定'
            }}
          </el-button>
        </div>
      </el-dialog>

      <userModal
        ref="userModal"
        v-if="userModalOpen"
        :multiple="userType === 0"
        :handleUserSubmit="handleUserSubmit"
        :close="closeUserModal"
        :open="userModalOpen"
        :pageSizes="[100,200,300,500]"
      />

      <course-modal
        ref="courseModal"
        v-if="courseModalShow"
        :open="courseModalShow"
        :close="closeCourseModal"
        :tags="tags"
        :submit="handleCourseSubmit"
      />

      <library-modal
        ref="libraryModal"
        v-if="libraryModalOpen"
        :open="libraryModalOpen"
        :close="closeLibraryModal"
        :tags="tags"
        @submit="handleLibrarySubmit"
      />

      <test-paper-modal
        ref="testPaperModal"
        v-if="testPaperModalOpen"
        :open="testPaperModalOpen"
        :close="closeTestPaperModal"
        :tags="tags"
        :submit="handleTestPaperSubmit"
      />

    </div>
  </div>
</template>

<script>
import userModal from "@/views/trainPlan/userModal.vue";
import libraryModal from "@/views/trainPlan/library.vue"
import testPaperModal from '@/views/trainPlan/testPaper.vue'
import {categoryTreeList, tagList, trainPlanInfo} from "@/api/edu/trainPlan";
import courseModal from '@/views/trainPlan/course.vue'

export default {
  name: 'create',
  components: {userModal, libraryModal, testPaperModal, courseModal},
  props: {
    id: {
      type: Number,
      default: null
    },
    open: {
      type: Boolean,
      default: false
    },
    close: {
      type: Function,
      default: () => {
      }
    }
  },
  dicts: ['exam_question_type', 'train_plan_train_category'],
  data() {
    return {
      tags: [],
      categories: [],
      title: '',
      courseModalShow: false,
      testPaperModalOpen: false,
      libraryModalOpen: false,
      userModalOpen: false,
      submitLoading: false,
      timeRange: [],
      rules: {},
      userType: 0,
      courseList: [],
      userDepts: [],
      participants: [],
      trainDirector: {},
      examDirector: {},
      testPapers: [],
      questionLibraryRules: {},
      data: {
        planName: '',
        startTime: '',
        endTime: '',
        trainWorkHours: '',
        trainLecturer: '',
        userIds: '',
        trainType: '0',
        offlineTrainDirectorId: '',
        offlineTrainLecturer: '',
        offlineTrainLocation: '',
        onlineTrainCourseIds: '',
        examType: '0',
        offlineExamDirectorId: '',
        offlineExamLecturer: '',
        offlineExamLocation: '',
        onlineExamType: '1',
        onlineExamTestpaperIds: '',
        onlineExamLibraryRule: ''
      },
      info: {}
    }
  },
  watch: {
    participants: {
      handler(val) {
        this.userDepts = val.reduce((acc, cur) => {
          if (!acc.some(item => item.deptId === cur.deptId)) {
            acc.push(cur);
          }
          return acc;
        }, []).map(item => item.dept.deptName);
      },
      deep: true
    }
  },
  mounted() {
    if (this.id) {
      this.title = '编辑培训计划'
      this.getInfo()
    } else {
      this.title = '创建培训计划'
    }
    tagList().then(res => {
      this.tags = res.data
    })
    categoryTreeList().then(res => {
      this.categories = res.data.rows
    })
  },
  methods: {
    getInfo() {
      trainPlanInfo(this.id).then(res => {
        this.data = {...res.data}
        this.data.knowledgeCategoryId = this.data.knowledgeCategoryId.split(",")
        this.timeRange.push(res.data.startTime)
        this.timeRange.push(res.data.endTime)
        this.participants = res.data.users
        this.userDepts = res.data.userDepts.split(",")
        this.trainDirector = res.data.offlineTrainDirector
        this.examDirector = res.data.offlineExamDirector
        this.testPapers = res.data.exams
        this.questionLibraryRules = JSON.parse(res.data.onlineExamLibraryRule)
      })
    },
    reset() {
      this.submitLoading = false
      this.data = {
        planName: '',
        startTime: '',
        endTime: '',
        userIds: '',
        trainType: '0',
        onlineTrainDirectorId: '',
        onlineTrainLecturer: '',
        onlineTrainLocation: '',
        offlineTrainCourseIds: '',
        examType: '0',
        offlineExamDirectorId: '',
        offlineExamLecturer: '',
        offlineExamLocation: '',
        onlineExamType: '0',
        onlineExamTestpaperIds: '',
        onlineExamLibraryRule: ''
      }
      this.timeRange = []
      this.participants = []
      this.trainDirector = {}
      this.examDirector = {}
      this.questionLibraryRules = []
    }
    ,
    removeParticipant(index) {
      this.participants.splice(index, 1)
    },
    removeTestPaper(index) {
      this.testPapers.splice(index, 1)
    },
    closeUserModal() {
      this.userModalOpen = false
    },
    closeTestPaperModal() {
      this.testPaperModalOpen = false
    },
    closeLibraryModal() {
      this.libraryModalOpen = false
    },
    closeCourseModal() {
      this.courseModalShow = false
    },
    removeCourse(index) {
      this.courseList.splice(index, 1)
    },
    handleUserClick(type) {
      this.userModalOpen = true;
      this.userType = type;
    },
    handleTestPaperSubmit(arr) {
      this.testPapers = arr
      this.testPaperModalOpen = false
    },
    handleLibrarySubmit(options) {
      console.log("iosda", options)
      this.questionLibraryRules = options
      this.libraryModalOpen = false
    },
    handleCourseSubmit(arr) {
      this.courseList = arr
      this.courseModalShow = false
    },
    handleUserSubmit(arr) {
      if (this.userType === 0) {
        this.participants = arr
      } else if (this.userType === 1) {
        this.trainDirector = arr[0]
      } else if (this.userType === 2) {
        this.examDirector = arr[0]
      }
      this.userModalOpen = false;
    },
    submit() {
      this.checkData().then(() => {
        this.submitLoading = true
        this.$emit('submit', this.data)
        console.log("data", this.data)
      })
    },
    endLoading() {
      this.submitLoading = false
    },
    async checkData() {
      if (!this.data.planName) {
        this.$message({
          type: "warning",
          message: "请输入计划名称"
        })
        throw new Error()
      }
      if (!this.data.trainCategoryId) {
        this.$message({
          type: "warning",
          message: "请选择计划分类"
        })
        throw new Error()
      }
      if (!this.data.knowledgeCategoryId || this.data.knowledgeCategoryId.length === 0) {
        this.$message({
          type: "warning",
          message: "请选择知识分类"
        })
        throw new Error()
      } else {
        this.data.knowledgeCategoryId = this.data.knowledgeCategoryId.toString()
      }
      if (this.timeRange.length === 0) {
        this.$message({
          type: "warning",
          message: "请选择起止时间"
        })
        throw new Error()
      } else {
        this.data.startTime = this.timeRange[0]
        this.data.endTime = this.timeRange[1]
      }
      if (!this.data.trainWorkHours) {
        this.$message({
          type: "warning",
          message: "请输入培训工时"
        })
        throw new Error()
      }
      if (!this.data.trainLecturer) {
        this.$message({
          type: "warning",
          message: "请输入培训讲师"
        })
        throw new Error()
      }
      if (this.participants.length === 0) {
        this.$message({
          type: "warning",
          message: "请选择至少一个参与人"
        })
        throw new Error()
      } else {
        let userIds = ''
        this.participants.forEach(p => {
          userIds = userIds + p.userId + ','
        })
        this.data.userIds = userIds.substring(0, userIds.length - 1)
        this.data.userDepts = this.userDepts.toString()
      }
      if (this.data.trainType === '0' && this.data.examType === '0') {
        this.$message({
          type: "warning",
          message: "培训类型与考试类型异常"
        })
        throw new Error()
      }
      if (this.data.trainType === '1') {
        if (this.courseList.length === 0) {
          this.$message({
            type: "warning",
            message: "请选择至少一个课程"
          })
          throw new Error()
        } else {
          let courseIds = ''
          this.courseList.forEach(p => {
            courseIds = courseIds + p.id + ','
          })
          console.log("courseList", this.courseList)
          this.data.onlineTrainCourseIds = courseIds.substring(0, courseIds.length - 1)
        }
      }
      if (this.data.trainType === '2') {
        if (Object.keys(this.trainDirector).length === 0) {
          this.$message({
            type: "warning",
            message: "请选择培训负责人"
          })
          throw new Error()
        } else {
          this.data.offlineTrainDirectorId = this.trainDirector.userId
        }
        if (!this.data.offlineTrainLecturer) {
          this.$message({
            type: "warning",
            message: "请输入培训讲师名称"
          })
          throw new Error()
        }
        if (!this.data.offlineTrainLocation) {
          this.$message({
            type: "warning",
            message: "请输入培训地点"
          })
          throw new Error()
        }
      }
      if (this.data.examType === '1') {
        if (this.data.onlineExamType === '1') {
          if (this.testPapers.length === 0) {
            this.$message({
              type: "warning",
              message: "请选择至少一份试卷"
            })
            throw new Error()
          } else {
            let testPaperIds = ''
            this.testPapers.forEach(p => {
              testPaperIds = testPaperIds + p.id + ','
            })
            this.data.onlineExamTestpaperIds = testPaperIds.substring(0, testPaperIds.length - 1)
          }
        } else {
          if (Object.keys(this.questionLibraryRules).length <= 0) {
            this.$message.warning("请配置题库")
          } else {
            this.data.onlineExamLibraryRule = JSON.stringify(this.questionLibraryRules)
          }
        }
      }
      if (this.data.examType === '2') {
        if (Object.keys(this.examDirector).length === 0) {
          this.$message({
            type: "warning",
            message: "请选择考试负责人"
          })
          throw new Error()
        } else {
          this.data.offlineExamDirectorId = this.examDirector.userId
        }
        if (!this.data.offlineExamLecturer) {
          this.$message({
            type: "warning",
            message: "请输入考试考官名称"
          })
          throw new Error()
        }
        if (!this.data.offlineExamLocation) {
          this.$message({
            type: "warning",
            message: "请输入考试地点"
          })
          throw new Error()
        }
      }
    }
  }
}
</script>

<style scoped>

</style>
